
package com.work.mvc.controler;

import com.vaadin.event.Action;
import com.work.db.entity.Overtime;
import com.work.mvc.*;
import com.work.mvc.view.table.OvertimeTable;
import com.work.util.AppUtils;

public class OvertimeTableController implements Action.Handler, Controller {

	private static final long serialVersionUID = 6730435312074361718L;

	private static final Action[] ACTIONS = new Action[]{Actions.ADD_ROW, Actions.DELETE_ROW, Actions.ENABLE_EDITING};
	
	private OvertimeTable view;
	
	public OvertimeTableController(OvertimeTable view) {
		this.view = view;
	}

	@Override
	public View getView()
	{
		return view;
	}

	@Override
	public Action[] getActions(Object target, Object sender)
	{
		return ACTIONS;
	}

	@Override
	public void handleAction(Action action, Object sender, Object target)
	{
		if (action == Actions.ADD_ROW) {
			Overtime rowToAdd = createEmptyRow();
			view.addItem(rowToAdd);
			view.refreshRowCache();
		} else if (action == Actions.DELETE_ROW) {
			if (target != null) {
				view.removeItem(target);
				view.refreshRowCache();
			}
		} else if (action == Actions.ENABLE_EDITING) {
			if (target != null) {
				view.setEditable(true);
			}
		} 
	}

	private Overtime createEmptyRow()
	{
		Overtime overtime = new Overtime();
		overtime.setBegin(AppUtils.createTime(0, 0, 0));
		overtime.setEnd(AppUtils.createTime(0, 0, 0));
		overtime.setDescription("");
		overtime.setWorkDay(view.getWorkDay());
		
		return overtime;
	}
}
